#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Author:  LJ
Email:   admin@attacker.club
Last Modified: 2020-02-11 12:24:49


aliyun-python-sdk-core-v3 aliyun-python-sdk-alidns
'''

import re,json,requests,datetime
import configparser
from aliyunsdkcore.client import AcsClient
from aliyunsdkalidns.request.v20150109.DescribeSubDomainRecordsRequest import DescribeSubDomainRecordsRequest
from aliyunsdkalidns.request.v20150109.AddDomainRecordRequest import AddDomainRecordRequest
from aliyunsdkalidns.request.v20150109.UpdateDomainRecordRequest import UpdateDomainRecordRequest
from aliyunsdkcore.acs_exception.exceptions import ServerException



# 配置文件设置
def ddns_config(filename):
    config = configparser.ConfigParser()
    config.read(filename) 
    config.sections()
    return config


# 获取出口地址
def getip():
    try:
        req = requests.get(url1, timeout=3)
        if req.status_code != requests.codes.ok:
            req = requests.get(url2, timeout=3)
    except Exception as e:
        print(e)

    finally:
        print("获取ip网站:",req.url)
        ipaddr = re.findall(r"\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b", req.text)
        return ipaddr[0]

# 查询解析
def Describe_SubDomain_Records(client, record_type, subdomain):
    request = DescribeSubDomainRecordsRequest()
    request.set_accept_format('json')

    request.set_Type(record_type)
    request.set_SubDomain(subdomain)

    response = client.do_action_with_exception(request)
    response = str(response, encoding='utf-8')
    relsult = json.loads(response)
    return relsult


# 添加解析
def add_record(client, priority, ttl, record_type, value, rr, domainname):
    request = AddDomainRecordRequest()
    request.set_accept_format('json')

    request.set_Priority(priority)
    request.set_TTL(ttl)
    request.set_Value(value)
    request.set_Type(record_type)
    request.set_RR(rr)
    request.set_DomainName(domainname)

    response = client.do_action_with_exception(request)
    response = str(response, encoding='utf-8')
    relsult = json.loads(response)
    return relsult

# 更新解析
def update_record(client, priority, ttl, record_type, value, rr, record_id):
    request = UpdateDomainRecordRequest()
    request.set_accept_format('json')

    request.set_Priority(priority)
    request.set_TTL(ttl)
    request.set_Value(value)
    request.set_Type(record_type)
    request.set_RR(rr)
    request.set_RecordId(record_id)

    response = client.do_action_with_exception(request)
    response = str(response, encoding='utf-8')
    return response


if __name__ == "__main__":
    # 配置信息
    cf = ddns_config('ddns.conf')
    url1 = cf['QueryURL']['url1']
    url2 = cf['QueryURL']['url2']
    AK = cf['Aliyunak']['AccessKeyId']
    AS = cf['Aliyunak']['AccessKeySecret']

    subdomain = cf['Dns record']['subdomain']
    domian = '.'.join(subdomain.split('.')[-2:])
    host = subdomain.split('.')[0]
    ipaddr = getip()

    now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')


    # 创建AcsClient实例
    client = AcsClient(AK, AS, "cn-hangzhou")

    # 查询：域名是否解析
    des_relsult = Describe_SubDomain_Records(client, "A", subdomain)
    # print (des_relsult)

    # 添加：解析记录不存在则添加一条记录
    if des_relsult["TotalCount"] == 0:
        add_relsult = add_record(client, "5", "600", "A", ipaddr, host, domian)

    # 更新: 更新ip
    else:
        record_id = des_relsult["DomainRecords"]["Record"][0]["RecordId"]
        try:
            update_record(client, "5", "600", "A", ipaddr, host, record_id)
        except   Exception as e:
            print('%s [%s] 解析已存在' % (now,ipaddr))
        else:
            print('%s [%s] 记录已更新 !!!' % (now,ipaddr))